package leetcode.offer_two_special.backtrack;

import java.util.LinkedList;
import java.util.List;

/**
 * @author mazouri
 * @create 2021-09-20 9:48
 */
public class _85_generateParenthesis {
    List<String> res = new LinkedList<>();
    StringBuilder sb = new StringBuilder();
    int n;

    public List<String> generateParenthesis(int n) {
        this.n = n;
        backtrack(n, n);
        return res;
    }

    private void backtrack(int left, int right) {
        if (sb.length() == this.n * 2) {
            res.add(sb.toString());
            return;
        }

        if (left > right) {
            return;
        }

        if (left > 0) {
            sb.append("(");
            backtrack(left - 1, right);
            sb.deleteCharAt(sb.length() - 1);
        }

        if (right > 0) {
            sb.append(")");
            backtrack(left, right - 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
